package com.yidian.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import com.yidian.server.order.OrderService;
import com.yidian.server.pay.WeixinPayService;
import com.yidian.utils.HttpClient;
import com.yidian.wxsdk.Config;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @author whb
 * @create 2021-09-15 10:51
 * @desciption 微信支付服务接口实现类
 */
@Service
public class WeixinPayServiceImpl implements WeixinPayService {
    @Autowired
    private Config config;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 生成微信支付二维码
     *
     * @param orderId   订单号
     * @param money     支付金额（分）
     * @param notifyUrl 回调地址
     * @return
     */
    @Override
    public Map createNative(String orderId, Integer money, String notifyUrl,String... attach) {
        try {
            //1.封装请求参数
            Map<String, String> map = new HashMap<>();
            map.put("appid", config.getAppID());//公众账号ID
            map.put("mch_id", config.getMchID());//商户号
            map.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符码
            map.put("body", "易点商城");//商品描述
            map.put("out_trade_no", orderId);//订单号
            map.put("total_fee", money + "");//金额
            map.put("spbill_create_ip", "127.0.0.1");//终端IP
            map.put("notify_url", notifyUrl);//回调地址
            map.put("trade_type", "NATIVE");//交易类型
            if(attach!=null && attach.length>0){
                map.put("attach",attach[0]);
            }

            //2.发送请求
            String xmlParam = WXPayUtil.generateSignedXml(map, config.getKey());//xml格式的参数
            WXPayRequest wxPayRequest = new WXPayRequest(config);
            String xmlResponse = wxPayRequest.requestWithCert("/pay/unifiedorder", null, xmlParam, false);

            //解析返回结果
            Map<String, String> mapResult = WXPayUtil.xmlToMap(xmlResponse);

            //封装返回数据
            Map mapReturn = new HashMap();
            mapReturn.put("code_url", mapResult.get("code_url"));//支付地址，用于生成支付二维码
            mapReturn.put("total_fee", money + "");//支付金额（分）
            mapReturn.put("out_trade_no", orderId);//订单号
            return mapReturn;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap();
        }
    }

    /**
     * 根据微信回调信息，改变订单状态
     * @param xmlResult
     */
    @Override
    public void notifyLogic(String xmlResult) {
        try {
            Map<String, String> map = WXPayUtil.xmlToMap(xmlResult);//将xml格式的回调信息解析成map集合
            boolean signatureValid = WXPayUtil.isSignatureValid(map, config.getKey());//验证签名
            if (signatureValid){
                if ("SUCCESS".equals(map.get("result_code"))){
                    //更新订单的数据，并记录订单变动的日志，并向rabbitmq通知交换机中发送成功消息
                    orderService.updatePayStatus(map.get("out_trade_no"),map.get("transaction_id"));
                    rabbitTemplate.convertAndSend("webnotify","",map.get("out_trade_no"));
                }else {
                    //支付失败，记录日志
                }
            }else{
                //非法订单，记录日志
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 微信支付接口：查询订单
     * @param orderId 订单号
     * @return
     */
    @Override
    public Map queryPayStatus(String orderId) {
        Map param = new HashMap();
        param.put("appid", config.getAppID());//公众账号ID
        param.put("mch_id", config.getMchID());//商户号
        param.put("out_trade_no", orderId);//订单号
        param.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符码
        String url="https://api.mch.weixin.qq.com/pay/orderquery";//微信查询订单接口URL地址
        try {
            String xmlParam=WXPayUtil.generateSignedXml(param, config.getKey());//使用微信支付工具类将map集合转化成xml
            HttpClient client=new HttpClient(url);
            client.setHttps(true);
            client.setXmlParam(xmlParam);
            client.post();
            String result = client.getContent();
            System.out.println(result);
            Map<String,String> map=WXPayUtil.xmlToMap(result);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 关闭支付订单
     * @param orderId
     * @return
     */
    @Override
    public Map<String, String> closePay(String orderId) {
        Map param = new HashMap();
        param.put("appid", config.getAppID());//公众账号ID
        param.put("mch_id", config.getMchID());//商户号
        param.put("out_trade_no", orderId);//订单号
        param.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符码
        String url="https://api.mch.weixin.qq.com/pay/closeorder";//微信关闭支付订单接口URL地址

        try {
            String xmlParam=WXPayUtil.generateSignedXml(param, config.getKey());//使用微信支付工具类将map集合转化成xml
            HttpClient httpClient=new HttpClient(url);//发送请求
            httpClient.setHttps(true);//https
            httpClient.setXmlParam(xmlParam);//提交参数
            httpClient.post();//提交
            String content = httpClient.getContent();//获取返回数据
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            System.out.println(resultMap);
            return resultMap;//将返回数据解析成map集合
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("close order failed..");
            return new HashMap<>();
        }
    }
}
